/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Google Code Wiki Viewer.
 *
 * The Initial Developer of the Original Code is Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Atte Kemppilä <atte.kemppila@iki.fi>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */


/*
 * Parts of this file is copied from Mozilla Toolkit filepicker:
 * http://mxr.mozilla.org/mozilla2.0/source/toolkit/components/filepicker/content/filepicker.js
 * See preference: ui.allow_platform_file_picker
 */


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");

Cu.import("resource://GoogleCodeWikiViewer/FileView.jsm");


const gcwv =
{
    get selectedFile()
    {
        let files = this.treeView.selectedFiles;
        return ((files.length > 0) ? files[0] : null);
    },
    
    onLoad: function()
    {
        Cu.import("resource://GoogleCodeWikiViewer/common.jsm", this);
        
        this.strings = document.getElementById("strings");
        
        this.mainWindow =
            window.
                QueryInterface(Ci.nsIInterfaceRequestor).
                getInterface(Ci.nsIWebNavigation).
                QueryInterface(Ci.nsIDocShellTreeItem).
                rootTreeItem.
                QueryInterface(Ci.nsIInterfaceRequestor).
                getInterface(Ci.nsIDOMWindow);
        
        this.treeView = new FileView();
        this.treeView.setFilter("*.wiki");
        this.treeView.sort(FileView.sortName, false);
        
        let tree = document.getElementById("tree_files");
        tree.treeBoxObject.view = this.treeView;
        
        try
        {
            let dir = this.prefs.getComplexValue("lastDir", Ci.nsILocalFile);
            this.openDirectoryAsync(dir);
        }
        catch (ex) { /* ignore */ }
    },
    
    onTreeDblClick: function(e)
    {
        if (e.button != 0)
            return;
        
        if (e.originalTarget.localName != "treechildren")
            return;
        
        this.openSelected();
    },
    
    onTreeKeyPress: function(e)
    {
        switch (e.keyCode)
        {
            case KeyEvent.DOM_VK_RETURN: this.openSelected(); return;
            case KeyEvent.DOM_VK_UP:     if (e.altKey) this.openParentDir(); return;
        }
    },
    
    openParentDir: function()
    {
        if (this.dir && this.dir.parent)
            this.openDirectoryAsync(this.dir.parent);
    },
    
    openDirPicker: function()
    {
        let filePicker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
        filePicker.init(window, this.strings.getString("dirPicker.title"), Ci.nsIFilePicker.modeGetFolder);
        filePicker.displayDirectory = this.dir;
        
        let result = filePicker.show();
        if (result != Ci.nsIFilePicker.returnOK)
            return;
        
        this.openDirectory(filePicker.file);
    },
    
    openSelected: function()
    {
        let file = this.selectedFile;
        if (! file)
            return;
        else if (file.isDirectory())
            this.openDirectory(file);
        else if (file.isFile())
            this.openFile(file);
    },
    
    refresh: function()
    {
        if (this.dir)
            this.openDirectoryAsync(this.dir);
    },
    
    openDirectory: function(dir)
    {
        window.setCursor("wait");
        
        try
        {
            this.treeView.setDirectory(dir);
            this.dir = dir;
            
            let tbox = document.getElementById("textbox_path");
            tbox.value = dir.path;
            tbox.tooltipText = dir.path;
            
            // scroll the end of the textbox into view (any simpler way?)
            tbox.editor.endOfDocument();
            tbox.editor.selectionController.scrollSelectionIntoView(
                Ci.nsISelectionController.SELECTION_NORMAL,
                Ci.nsISelectionController.SELECTION_FOCUS_REGION,
                0);
            
            this.prefs.setComplexValue("lastDir", Ci.nsILocalFile, dir);
        }
        finally
        {
            window.setCursor("auto");
        }
    },
    
    openDirectoryAsync: function(dir)
    {
        let self = this;
        window.setTimeout(function() { self.openDirectory(dir); }, 0);
    },
    
    openFile: function(file)
    {
        let fileUri = Services.io.newFileURI(file);
        
        let tabbrowser = this.mainWindow.getBrowser();
        let tabCount = tabbrowser.browsers.length;
        for (let index = 0; index < tabCount; index++)
        {
            let browser = tabbrowser.getBrowserAtIndex(index);
            if (browser.currentURI.spec == fileUri.spec)
            {
                tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];
                return;
            }
        }
        
        tabbrowser.selectedTab = tabbrowser.addTab(fileUri.spec);
    }
}
